import { MdSnackBar } from '@angular/material';
import { LoadMaskService } from './../../component/primeng/loadmask/loadmask.module';
import { FNCManager } from './../../common/fncManager';
import { SyncDataService } from './../../service/sync.service';
import { SystemService } from './../../service/system.service';
import { NavigateService } from './../../service/navigate.service';
import { MessageBoxService, GrowlMessageType } from './../../component/messageBoxService';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Authentication } from "../../service/index";
import { StoreService } from './../../service/store.service';
import { loadingMask } from './../../component/decorators';

@Component({
    //moduleId: module.id,
    selector: 'stores',
    templateUrl: './stores.component.html',
    styleUrls: ['./stores.component.scss']
})
export class StoreComponent implements OnInit {
    constructor(
        private storeService: StoreService,
        private router: NavigateService,
        private activatedRoute: ActivatedRoute,
        private msgSvr: MessageBoxService,
        private authSvr: Authentication,
        private sysSvr: SystemService,
        private syncSvr: SyncDataService,
        public snackBar: MdSnackBar
    ) { }
    stores = [];
    private sub;
    cloudHost = this.storeService.CloudHost + ":" + this.storeService.CloudPort;
    count = 0;
    checkArrayList = [];

    async ngOnInit() {
        this.router.registGoBack(() => {
            let backBtn = document.getElementById("back-btn");
            if (backBtn) {
                backBtn.click();
            }
        });
        this.stores = [];
        let storeUser = this.storeService.StoreOwner;
        this.getStoreList(storeUser.user.id);
    }

    async chooseStore(store) {
        LoadMaskService.Current.show();
        this.storeService.CurrentStore = store;
        //切换店铺之后需要清空indexedDB中的数据，避免新店铺的数据和上一个店铺混在一起
        this.syncSvr.ClearAll();
        let ldcconfig = await this.authSvr.getLDCConfig(store.id);
        if (!ldcconfig || !ldcconfig.host) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, "获取店铺配置失败");
            LoadMaskService.Current.hide();
            return;
        } else {
            this.checkEnv(this);
        }
    }
    goBack() {
        return this.router.navigate(["storeLogin"]);
    }
    /**
     * 获取店铺列表
     */
    @loadingMask()
    private async getStoreList(userId: string) {
        try {
            this.stores = await this.storeService.getStores(userId);
        } catch (error) {
            this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "获取店铺失败");
        }
    }

    /**
    * 环境检测，FNS,FBS等是否正常连接
    * @param  {} that 当前作用域
    */
    checkEnv(that) {
        FNCManager.Current.AppComponent_Connect();
        that.checkArrayList = that.sysSvr.GetLDCServiceList();
        let fnsSvr = that.checkArrayList.find(function (element) {
            return (<any>element).name == "FNS";
        });

        that.sysSvr.LDCServiceChangedEvent = function (sender) {
            that.count++;
            if (that.count == that.checkArrayList.length) {
                that.checkIsPass();
            }
        }
        that.sysSvr.CheckLDCService();
    }

    /**
     * 判断是否各项环境正常连接
     */
    checkIsPass() {
        this.count = 0;
        let flag = true;
        for (let item of this.checkArrayList) {
            if (item.status == "failed") {
                flag = false;
            }
        }
        LoadMaskService.Current.hide();
        if (flag) {
            this.router.navigate(["bindDevice"]);
        } else {
            this.router.navigate(["checkEnv"]);
        }
    }
}